/**
 * Ant Design Pro v4 use `@ant-design/pro-layout` to handle Layout.
 *
 * @see You can view component api by: https://github.com/ant-design/ant-design-pro-layout
 */
import type { MenuDataItem, BasicLayoutProps as ProLayoutProps, Settings } from '@ant-design/pro-layout';
import ProLayout, { DefaultFooter } from '@ant-design/pro-layout';
import React, { useEffect, useMemo, useRef } from 'react';
import type { Dispatch } from 'umi';
import { Link, useIntl, connect, history } from 'umi';
import { Result, Button } from 'antd';
import Authorized from '@/utils/Authorized';
import RightContent from '@/components/GlobalHeader/RightContent';
import type { ConnectState } from '@/models/connect';
// import logo from '../assets/logo.png';
import routes from '../../config/routes';
import TabPages from '@/components/TabPages';

const noMatch = (
  <Result
    status={403}
    title="403"
    subTitle="Sorry, you are not authorized to access this page."
    extra={
      <Button type="primary">
        <Link to="/user/login">Go Login</Link>
      </Button>
    }
  />
);
export type BasicLayoutProps = {
  breadcrumbNameMap: Record<string, MenuDataItem>;
  route: ProLayoutProps['route'] & {
    authority: string[];
  };
  settings: Settings;
  dispatch: Dispatch;
} & ProLayoutProps;
export type BasicLayoutContext = { [K in 'location']: BasicLayoutProps[K] } & {
  breadcrumbNameMap: Record<string, MenuDataItem>;
};
/** Use Authorized check all menu item */

const defaultFooterDom = <DefaultFooter copyright="医疗科技股份有限公司" links={false}/>;

const BasicLayout: React.FC<BasicLayoutProps> = props => {
  const menuDataRef = useRef<MenuDataItem[]>([]);

  const menuDataRender = (menuList: MenuDataItem[]): MenuDataItem[] => {
    return menuList.map(item => {
      const localItem = { ...item,
        children: item.children ? menuDataRender(item.children) : undefined
      };
      return (Authorized.check(item.authority, localItem, null) as MenuDataItem);
    });
  };

  const {
    dispatch,
    settings,
    location = {
      pathname: '/'
    }
  } = props;
  useEffect(() => {
    if (dispatch) {
      dispatch({
        type: 'user/fetchCurrent'
      });
    }
  }, []);
  /** Init variables */

  const handleMenuCollapse = (payload: boolean): void => {
    if (dispatch) {
      dispatch({
        type: 'global/changeLayoutCollapsed',
        payload
      });
    }
  };

  const menuData = (menuList: any, result: any[], auth: []) => {
    menuList.map((item: any) => {
      if (item.routes && item.routes.length > 0) {
        menuData(item.routes, result, item.authority);
      } // var data = Authorized.check(item.authority, localItem, null) as MenuDataItem;
      if (item.authority) {
        // if(item.path==='/order/sent'){
        //   if(sessionStorage.getItem('loginName')=='jgu'){
        //     item.authority = ['checker','admin','financial','store','wbsc','analysis']
        //   }
        // }
        result.push({
          path: item.path,
          authority: item.authority
        });
      } else {
        result.push({
          path: item.path,
          authority: auth
        });
      }
    });
  }; // get children authority


  const authorized = useMemo(() => {
    // if(menuDataRef.current&&menuDataRef.current.length>0){
    //   console.log(location.pathname,=======2222222=================);
    //   return getMatchMenu(location.pathname || '/', menuDataRef.current).pop() || {authority: undefined}
    // }
    var result: any[] = [];
    menuData(routes, result, []); //console.log(result,sessionStorage.getItem('access'));
    // console.log(data,location.pathname,menuDataRef.current);

    let current: string = (location.pathname as string);

    for (let i = 0; i < result.length; i++) {
      let loc: string = result[i].path;

      if (loc === current || loc + '/' === current) {
        return {
          authority: result[i].authority
        };
      }
    }

    return {
      authority: undefined
    };
  }, [location.pathname]);
  const {
    formatMessage
  } = useIntl();
  return <ProLayout  formatMessage={formatMessage} {...props} {...settings} onCollapse={handleMenuCollapse} onMenuHeaderClick={()=>{}} menuItemRender={(menuItemProps, defaultDom) => {
    if (menuItemProps.isUrl || !menuItemProps.path || location.pathname === menuItemProps.path) {
      return defaultDom;
    }

    return <Link to={menuItemProps.path}>{defaultDom}</Link>;
  }} breadcrumbRender={(routers = []) => [{
    path: '/',
    breadcrumbName: formatMessage({
      id: 'menu.home'
    })
  }, ...routers]} itemRender={(route, params, routes, paths) => {
    const first = routes.indexOf(route) === 0;
    return first ? <Link to={paths.join('/')}>{route.breadcrumbName}</Link> : <span>{route.breadcrumbName}</span>;
  }} footerRender={() => defaultFooterDom} menuDataRender={data => {
    return menuDataRender(data);
  }} rightContentRender={() => <RightContent/>} postMenuData={menuData => {
    menuDataRef.current = menuData || [];
    return menuData || [];
  }}>
      <Authorized authority={authorized?.authority} noMatch={noMatch}>
          {
        /* {children } */
      }
          <TabPages {...props} maxTab={6} preventReload remberRefresh errorPage="/exception/404"/>
      </Authorized>
    </ProLayout>;
};

export default connect(({
  global,
  settings
}: ConnectState) => ({
  collapsed: global.collapsed,
  settings
}))(BasicLayout);